package com.yfq.springframework.util;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * @author 姚凤桥
 * @date 2022/12/5 21:43
 * @description
 */
public class ClassUtils {
    public static ClassLoader getDefaultClassLoader() {
        return ClassUtils.class.getClassLoader();
    }

    public static boolean isCglibProxyClass(Class<?> clazz) {
        return clazz != null && isCglibClassName(clazz.getName());
    }

    /**
     * cglib代理的类名有$$符号
     */
    public static boolean isCglibClassName(String name) {
        return !StringUtils.isEmpty(name) && name.contains("$$");
    }

    /**
     * 根据包名、注解来扫描包下的class
     */
    public static List<Class<?>> scanPackageByAnnotation(String basePackage, Class<?> clazz) {
        List<Class<?>> classes = new ArrayList<>();

        File file = new File(basePackage);
        if (!file.exists()) {
            throw new RuntimeException("没有找到指定路径：" + basePackage);
        }

        try {
            File[] files = file.listFiles();
            for (File f : files) {
                if (!f.isDirectory() && f.getName().endsWith(".class")) {
                    String name = f.getName();
                    String className = name.substring(0, name.indexOf(".class"));
                    Class<?> aClass = Class.forName(className);
                    classes.add(aClass);
                }
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
            throw new RuntimeException("包扫描错误！" + e);
        }

        return classes;

    }
}
